import { apiService } from './api';

// 文件相关类型定义
export interface FileItem {
  id: string;
  name: string;
  type: 'file' | 'folder';
  size: number;
  mimeType: string;
  extension: string;
  path: string;
  parentId?: string;
  createdAt: string;
  updatedAt: string;
  createdBy: string;
  createdByName: string;
  permissions: FilePermission[];
  isShared: boolean;
  shareLink?: string;
  downloadCount: number;
  tags: string[];
  description?: string;
  thumbnail?: string;
  previewUrl?: string;
  downloadUrl: string;
}

export interface FilePermission {
  userId: string;
  userName: string;
  permission: 'read' | 'write' | 'admin';
  grantedAt: string;
  grantedBy: string;
}

export interface FileVersion {
  id: string;
  fileId: string;
  version: string;
  size: number;
  createdAt: string;
  createdBy: string;
  createdByName: string;
  comment?: string;
  downloadUrl: string;
}

export interface FileUploadProgress {
  fileId: string;
  fileName: string;
  progress: number;
  status: 'uploading' | 'completed' | 'failed';
  error?: string;
}

export interface FileSearchParams {
  keyword?: string;
  type?: 'file' | 'folder';
  mimeType?: string;
  extension?: string;
  createdBy?: string;
  tags?: string[];
  dateRange?: {
    start: string;
    end: string;
  };
  sizeRange?: {
    min: number;
    max: number;
  };
  page?: number;
  size?: number;
  sortBy?: 'name' | 'size' | 'createdAt' | 'updatedAt';
  sortOrder?: 'asc' | 'desc';
}

export interface FileShareConfig {
  expireAt?: string;
  password?: string;
  allowDownload: boolean;
  allowPreview: boolean;
  maxDownloads?: number;
}

export interface FolderTree {
  id: string;
  name: string;
  path: string;
  parentId?: string;
  children: FolderTree[];
  fileCount: number;
  totalSize: number;
}

// 文件管理服务类
class FileService {
  // 获取文件列表
  async getFiles(folderId?: string, params?: {
    page?: number;
    size?: number;
    sortBy?: string;
    sortOrder?: 'asc' | 'desc';
  }): Promise<{
    content: FileItem[];
    totalElements: number;
    totalPages: number;
    size: number;
    number: number;
  }> {
    const queryParams = {
      folderId,
      ...params
    };
    return apiService.get('/files', queryParams);
  }

  // 获取文件详情
  async getFile(id: string): Promise<FileItem> {
    return apiService.get(`/files/${id}`);
  }

  // 创建文件夹
  async createFolder(name: string, parentId?: string): Promise<FileItem> {
    return apiService.post('/files/folders', {
      name,
      parentId
    });
  }

  // 上传文件
  async uploadFile(
    file: File,
    folderId?: string,
    onProgress?: (progress: FileUploadProgress) => void
  ): Promise<FileItem> {
    const formData = new FormData();
    formData.append('file', file);
    if (folderId) {
      formData.append('folderId', folderId);
    }

    // 模拟上传进度
    if (onProgress) {
      onProgress({
        fileId: '',
        fileName: file.name,
        progress: 100,
        status: 'completed'
      });
    }

    return apiService.post('/files/upload', formData);
  }

  // 批量上传文件
  async uploadFiles(
    files: File[],
    folderId?: string,
    onProgress?: (progress: FileUploadProgress[]) => void
  ): Promise<FileItem[]> {
    const uploadPromises = files.map(file => this.uploadFile(file, folderId));
    return Promise.all(uploadPromises);
  }

  // 重命名文件/文件夹
  async renameFile(id: string, name: string): Promise<FileItem> {
    return apiService.put(`/files/${id}/rename`, { name });
  }

  // 移动文件/文件夹
  async moveFile(id: string, targetFolderId?: string): Promise<FileItem> {
    return apiService.put(`/files/${id}/move`, { targetFolderId });
  }

  // 复制文件/文件夹
  async copyFile(id: string, targetFolderId?: string, newName?: string): Promise<FileItem> {
    return apiService.post(`/files/${id}/copy`, {
      targetFolderId,
      newName
    });
  }

  // 删除文件/文件夹
  async deleteFile(id: string): Promise<void> {
    return apiService.delete(`/files/${id}`);
  }

  // 批量删除文件
  async deleteFiles(ids: string[]): Promise<void> {
    return apiService.post('/files/batch/delete', { ids });
  }

  // 搜索文件
  async searchFiles(params: FileSearchParams): Promise<{
    content: FileItem[];
    totalElements: number;
    totalPages: number;
    size: number;
    number: number;
  }> {
    return apiService.get('/files/search', params);
  }

  // 获取文件夹树结构
  async getFolderTree(): Promise<FolderTree[]> {
    return apiService.get('/files/folders/tree');
  }

  // 获取文件版本历史
  async getFileVersions(fileId: string): Promise<FileVersion[]> {
    return apiService.get(`/files/${fileId}/versions`);
  }

  // 创建文件版本
  async createFileVersion(fileId: string, file: File, comment?: string): Promise<FileVersion> {
    const formData = new FormData();
    formData.append('file', file);
    if (comment) {
      formData.append('comment', comment);
    }
    return apiService.post(`/files/${fileId}/versions`, formData);
  }

  // 恢复文件版本
  async restoreFileVersion(fileId: string, versionId: string): Promise<FileItem> {
    return apiService.post(`/files/${fileId}/versions/${versionId}/restore`);
  }

  // 分享文件
  async shareFile(id: string, config: FileShareConfig): Promise<{
    shareLink: string;
    shareId: string;
  }> {
    return apiService.post(`/files/${id}/share`, config);
  }

  // 取消分享
  async unshareFile(id: string): Promise<void> {
    return apiService.delete(`/files/${id}/share`);
  }

  // 获取分享信息
  async getShareInfo(shareId: string): Promise<{
    file: FileItem;
    config: FileShareConfig;
    downloadCount: number;
  }> {
    return apiService.get(`/files/share/${shareId}`);
  }

  // 通过分享链接下载文件
  async downloadSharedFile(shareId: string, password?: string): Promise<Blob> {
    const params = password ? { password } : undefined;
    return apiService.get(`/files/share/${shareId}/download`, params);
  }

  // 设置文件权限
  async setFilePermissions(id: string, permissions: Omit<FilePermission, 'grantedAt' | 'grantedBy'>[]): Promise<void> {
    return apiService.put(`/files/${id}/permissions`, { permissions });
  }

  // 获取文件权限
  async getFilePermissions(id: string): Promise<FilePermission[]> {
    return apiService.get(`/files/${id}/permissions`);
  }

  // 下载文件
  async downloadFile(id: string): Promise<Blob> {
    return apiService.get(`/files/${id}/download`);
  }

  // 获取文件预览URL
  async getPreviewUrl(id: string): Promise<string> {
    const response: { previewUrl: string } = await apiService.get(`/files/${id}/preview`);
    return response.previewUrl;
  }

  // 获取文件缩略图
  async getThumbnail(id: string): Promise<string> {
    const response: { thumbnailUrl: string } = await apiService.get(`/files/${id}/thumbnail`);
    return response.thumbnailUrl;
  }

  // 添加文件标签
  async addFileTags(id: string, tags: string[]): Promise<FileItem> {
    return apiService.post(`/files/${id}/tags`, { tags });
  }

  // 移除文件标签
  async removeFileTags(id: string, tags: string[]): Promise<FileItem> {
    return apiService.post(`/files/${id}/tags/remove`, { tags });
  }

  // 更新文件描述
  async updateFileDescription(id: string, description: string): Promise<FileItem> {
    return apiService.put(`/files/${id}/description`, { description });
  }

  // 获取存储统计
  async getStorageStats(): Promise<{
    totalSize: number;
    usedSize: number;
    fileCount: number;
    folderCount: number;
    recentFiles: FileItem[];
    popularFiles: FileItem[];
  }> {
    return apiService.get('/files/stats');
  }

  // 清理回收站
  async emptyTrash(): Promise<void> {
    return apiService.delete('/files/trash');
  }

  // 从回收站恢复文件
  async restoreFromTrash(id: string): Promise<FileItem> {
    return apiService.post(`/files/trash/${id}/restore`);
  }

  // 获取回收站文件
  async getTrashFiles(): Promise<FileItem[]> {
    return apiService.get('/files/trash');
  }
}

export const fileService = new FileService();
export default fileService;